package cn.com.zsw.gblog.modules.user.service.impl;

import cn.com.zsw.gblog.modules.user.mapper.PermissionMapper;
import cn.com.zsw.gblog.modules.user.mapper.RoleMapper;
import cn.com.zsw.gblog.modules.user.mapper.UserMapper;
import cn.com.zsw.gblog.modules.user.entity.GbUserEntity;
import cn.com.zsw.gblog.modules.user.entity.RoleEntity;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: shiwangZhou
 * @Description:
 * @Date: 2020-07-01 14:33
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    UserMapper userMapper;
    @Resource
    RoleMapper roleMapper;
    @Resource
    PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        GbUserEntity gbUser = userMapper.selectOne(Wrappers.<GbUserEntity>lambdaQuery().eq(GbUserEntity::getUsername, username));
        if (gbUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<RoleEntity> roles = roleMapper.selectRolesByUserId(gbUser.getId());
        gbUser.setRoles(roleMapper.selectRolesByUserId(gbUser.getId()));
        List<String> list = permissionMapper.selectPermissionsByUserId(gbUser.getId());
        HashSet<SimpleGrantedAuthority> set = new HashSet<>();
        roles.stream().map(RoleEntity::getName).collect(Collectors.toList()).forEach(s -> set.add(new SimpleGrantedAuthority(s)));
        list.forEach(s -> set.add(new SimpleGrantedAuthority(s)));
        return new org.springframework.security.core.userdetails.User(username, gbUser.getPassword(), set);
    }
}